package org.demo.warehouse.common.utils;

import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;

public class StatisticCollector implements Collector<Map<String, Object>, Map<String, List<Object>>, Map<String, List<Object>>> {

    public static StatisticCollector getInstance(){
        return new StatisticCollector();
    }

    @Override
    public Supplier<Map<String, List<Object>>> supplier() {
        return HashMap::new;
    }

    @Override
    public BiConsumer<Map<String, List<Object>>, Map<String, Object>> accumulator() {
        return (out, in) -> {
            List<Object> keys = out.computeIfAbsent("keys", (key) -> new ArrayList<>());
            keys.add(in.get("key"));
            List<Object> values = out.computeIfAbsent("values", (key) -> new ArrayList<>());
            values.add(in.get("value"));
        };
    }

    @Override
    public BinaryOperator<Map<String, List<Object>>> combiner() {
        return (out1, out2) -> {
            out1.putAll(out2);
            return out1;
        };
    }

    @Override
    public Function finisher() {
        return Function.identity();
    }

    @Override
    public Set<Characteristics> characteristics() {
        return Collections.unmodifiableSet(EnumSet.of(Characteristics.CONCURRENT));
    }
}
